<?php

namespace App\Http\Controllers;

use App\Models\Message;
use Illuminate\Http\Request;
use DfaFilter\SensitiveHelper;

class MessageController extends Controller
{
    public function listByReceive()
    {
        $pn = request()->input('pn', config('api.page_num'));
        $recId = request()->input('rec_id', 0);
        $list = Message::where('receive', $recId)
            ->select('id', 'send', 'reply', 'msg', 'created_at')
            ->with('sendUser:id,name')
            ->orderBy('created_at', 'desc')
            ->paginate($pn);
        return response()->json(['recode' => 1,
            'data' => ['last_page' => $list->lastPage()
                , 'page' => $list->currentPage()
                , 'list' => $list->items()]]);
    }

    public function listBySend()
    {
        $pn = request()->input('pn', config('api.page_num'));
        $sendId = request()->input('send_id', 0);
        $list = Message::where('send', $sendId)
            ->select('id', 'receive', 'reply', 'msg', 'created_at')
            ->with('receiveUser:id,name')
            ->orderBy('created_at', 'desc')
            ->paginate($pn);
        return response()->json(['recode' => 1,
            'data' => ['last_page' => $list->lastPage()
                , 'page' => $list->currentPage()
                , 'list' => $list->items()]]);
    }

    public function sendMsg()
    {
        $send = request()->input('send', 0);
        $receive = request()->input('reveive', 0);
        $rep = request()->input('rep', '');
        $msg = request()->input('msg', '');

        $text=MessageController::checkSensitiveWords($msg);
        if (!$text){
            $message = new Message;
            $message->send = $send;
            $message->receive = $receive;
            $message->reply = $rep;
            $message->msg = $msg;

            $message->save();
            return response()->json(['recode' => 1,
                'msg' => '留言成功']);
        }else{
            return response()->json(['recode' => 0,
                'msg' => '包含铭感词汇，请注意用词']);
        }


    }

    public static function checkSensitiveWords($words)
    {
        $route = __DIR__.  '/../../../public/Sensitive_words.txt';
        $handle = SensitiveHelper::init()->setTreeByFile($route);
        $isLegal = $handle->islegal($words);//是否有敏感词
        if($isLegal) {
            return true;
        }else{
            return false;
        }
    }
}
